<!--
* @author luguoxiang
* @date 2021-09-07
* 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
-->
<template>
  <t-auto-complete :options="history" v-bind="$attrs" @focus="onfocus" @blur="onblur" @select="onselect" />
</template>
<script lang="ts" setup>
import { ref } from 'vue';

const props = defineProps({
  /**
   * 缓存key
   */
  code: {
    type: String,
    required: true,
  },
  /**
   * 限制历史数量
   */
  limit: {
    type: Number,
    default: 10,
  },
});
const emits = defineEmits(['focus', 'blur', 'select']);

const history = ref();
function push(e: string) {
  if (e && e.trim()) {
    const index = history.value.indexOf(e);
    if (index !== -1) {
      history.value.splice(index, 1);
    }
    history.value.unshift(e);
    history.value = history.value.slice(0, props.limit);
    localStorage.setItem(`LgHistoryInput:${props.code}`, JSON.stringify(history.value));
  }
}
function onfocus(e: any) {
  if (!Array.isArray(history.value)) {
    try {
      history.value = JSON.parse(localStorage.getItem(`LgHistoryInput:${props.code}`));
      if (!Array.isArray(history.value)) {
        history.value = [];
      }
    } catch (e) {
      history.value = [];
    }
  }
  emits('focus', e);
}
function onblur(e: any) {
  push(e.value);
  emits('blur', e);
}
function onselect(e: any) {
  push(e);
  emits('select', e);
}
</script>
<script lang="ts">
export default {
  name: 'LgHistoryInput',
};
</script>
